package com.xiaoshi.hander;

import com.xiaoshi.enums.JsonReturnEnums;
import com.xiaoshi.exception.PlatformException;
import com.xiaoshi.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常处理
 */
@Slf4j
@Configurable
public class BaseExceptionHandler {
    //捕捉普通的异常
    @ExceptionHandler(value = Exception.class)
    public JsonResult defaultErrorHandler(Exception e) {
        log.error("系统异常：", e);
        e.printStackTrace();
        return JsonResult.fail(e.getMessage());

    }

    //捕捉自己定义的异常（BusinessException.class）
    @ExceptionHandler(value = PlatformException.class)
    public JsonResult businessErrorHandler(PlatformException e) {
        log.error("业务异常", e);
        e.printStackTrace();
        //自己定义的运行时异常
        return JsonResult.fail(e.getStatus(),e.getMsg());
    }

    //空异常
    @ExceptionHandler(value = NullPointerException.class)
    public JsonResult nullPointerExceptionHandler(NullPointerException e) {
        log.error("未知空异常", e);
        e.printStackTrace();
        return JsonResult.fail(JsonReturnEnums.NULL_EXCE);
    }

    //
    @ExceptionHandler(value = AccessDeniedException.class)
    public JsonResult nullPointerExceptionHandler(AccessDeniedException e) {
        log.error("AccessDeniedException异常", e);
        e.printStackTrace();
        return JsonResult.fail(JsonReturnEnums.NO_PREM);
    }


    /***
     * 404处理
     * @param e
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public JsonResult notFountHandler(HttpServletRequest request, NoHandlerFoundException e) {
        String method = request.getMethod();
        String path = request.getRequestURI();
        log.info("404");
        return JsonResult.failFormat(JsonReturnEnums.SERVICE_NO_FIND_URL,path);
    }
}
